package gr.handmademarket.ui.views;

import gr.handmademarket.po.implementations.Product;
import gr.handmademarket.ui.pages.ProductDetailsPage;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.image.NonCachingImage;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.GridView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.resource.ContextRelativeResource;

/**
 * images grid view.
 */
public class ProductsListGrid 
extends GridView<Product>{


	/**
	 * Creates a new ProductsListGrid object. 
	 *
	 * @param id
	 * @param dataProvider
	 */
	public ProductsListGrid(String id, IDataProvider<Product> dataProvider) {
		super(id, dataProvider);
	}

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void populateEmptyItem(Item<Product> item) {
		// empty
	}

	@Override
	protected void populateItem(Item<Product> item) {
		AjaxLink<NonCachingImage> link = createAjaxLink(item.getModelObject());
		item.add(link);
	}
	
	/**
	 * @param product
	 * @return ajax link with the product thumbnail leading to product detail page.
	 */
	@SuppressWarnings("nls")
	private AjaxLink<NonCachingImage> createAjaxLink(Product product){
		final Product p = product;
		String path = "/images/products/" + p.getCode() + ".jpg"; 
		ContextRelativeResource resource = new ContextRelativeResource(path);
		NonCachingImage image = new NonCachingImage("img", resource);
		AjaxLink<NonCachingImage> ajaxLink = new AjaxLink<NonCachingImage>("link", new Model<NonCachingImage>(image)) {
			/**
			 * serialVersionUID
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				ProductDetailsPage page = new ProductDetailsPage(new CompoundPropertyModel<Product>(p));
				setResponsePage(page);
			}
		};
		ajaxLink.add(image);
		return ajaxLink;
	}

}
